<script lang="tsx" setup>
import { FormSchema } from '@/types/form'
import { TableColumn } from '@/types/table'
import { Table } from '@/components/Table/index'
import { dateFormatter } from '@/utils/formatTime'
import { moneyFormatter } from '@/utils/formatters'
import { statusMap, bindTypeDict } from './common'
import { ElTag, ElImage, ElButton } from 'element-plus'
import * as SkuApi from '@/api/client-mall/product/sku'
import * as SkuBindApi from '@/api/client-mall/product/sku/sku-bind'
import { getOSSURL } from '@/utils/oss'
import EditSkuForm from './edit-sku-form.vue'
import CheckoutConfigForm from './checkout-config-form.vue'

const route = useRoute()

const spuId = route.query.spuId as string | undefined

/** 表格字段 */
const columns: TableColumn[] = [
  {
    field: 'expand',
    type: 'expand'
  },
  {
    field: 'picUrl',
    label: '缩略图',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      const url = getOSSURL(cellValue)
      return cellValue ? (
        <ElImage
          class="w-20 h-20"
          src={url}
          preview-src-list={[url]}
          fit="cover"
          preview-teleported
        />
      ) : (
        <span>暂无图片</span>
      )
    }
  },
  {
    field: 'skuName',
    label: '套餐名称'
  },
  {
    field: 'spuName',
    label: '所属班型'
  },
  {
    field: 'price',
    label: '售价',
    formatter: moneyFormatter
  },
  {
    field: 'stock',
    label: '库存'
  },
  {
    field: 'warnStockLimit',
    label: '库存预警'
  },
  {
    field: 'status',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      const info = statusMap[cellValue]
      return <ElTag type={info.type}>{info.label}</ElTag>
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    formatter: dateFormatter
  },
  {
    field: 'updateTime',
    label: '更新时间',
    formatter: dateFormatter
  },
  {
    field: 'actions',
    label: '操作',
    fixed: 'right',
    width: 240,
    formatter: (row: Recordable) => (
      <>
        <ElButton
          type="primary"
          link
          v-hasPermi={[['train:product-sku:update']]}
          onClick={() => openCheckoutConfigForm(row.id)}
        >
          分润配置
        </ElButton>
        <ElButton
          type="primary"
          link
          v-hasPermi={[['train:product-sku:update']]}
          onClick={() => openForm('update', row.id)}
        >
          编辑
        </ElButton>
        <ElButton
          type="primary"
          link
          onClick={() =>
            // @ts-ignore
            elTableRef.value?.value.toggleRowExpansion(row)
          }
        >
          套餐服务
        </ElButton>
        <ElButton
          type="danger"
          link
          v-hasPermi={[['train:product-sku:delete']]}
          onClick={() => delList(row.id, false)}
        >
          删除
        </ElButton>
      </>
    )
  }
]

/** 表格相关方法 */
const {
  register: tableRegister,
  tableObject,
  tableMethods,
  elTableRef
} = useTable({
  getListApi: async (option: any) => {
    const { pageSize, pageNo, ...params } = option

    spuId && (params.spuId = spuId)

    const newParams = Object.entries(params).reduce((prev, [key, value]) => {
      value && (prev[key] = value)
      return prev
    }, {})

    // 调用接口获取直播列表
    const res = await SkuApi.getPage({ pageSize, pageNo, ...newParams })
    console.log('测试', res)
    // 初始化sku绑定的服务列表
    res.list.forEach((item: SkuApi.SkuVO) => {
      skuBindMap[item.id] = {
        loading: true,
        list: null
      }
    })

    return {
      list: res.list,
      total: res.total
    }
  },
  delListApi: async (option: Sku['id']) => {
    await SkuApi.del(option)
    return {}
  }
})
const { getList, setSearchParams, delList } = tableMethods

/** 初始化时加载列表 */
onMounted(getList)

/** 搜索栏 */
const searchFields: FormSchema[] = [
  {
    field: 'videoName',
    label: '套餐名称',
    component: 'Input',
    colProps: { span: 5 }
  }
]

/** 分润配置 */
const checkoutConfigFormRef = ref()
const openCheckoutConfigForm = (id: string) => {
  checkoutConfigFormRef.value.open(id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string) => {
  formRef.value.open(type, spuId, id)
}

const skuBindMap = reactive({}) // sku绑定的服务列表
const handleExpandChange = async (row: SkuApi.SkuVO) => {
  if (skuBindMap[row.id]?.list) return
  skuBindMap[row.id].loading = true
  try {
    const data = await SkuBindApi.listBySkuId(row.id)

    skuBindMap[row.id].list = data
  } finally {
    skuBindMap[row.id].loading = false
  }
}

/** 绑定类型格式化 */
const bindTypeFormatter = (val: number) => {
  const bindType = bindTypeDict.find((item) => item.value === val)

  return {
    type: bindType?.type,
    text: bindType?.label
  }
}
</script>

<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <Search :schema="searchFields" @search="setSearchParams">
      <template #actionMore>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['train:course:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 添加
        </el-button>
      </template>
    </Search>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <Table
      @register="tableRegister"
      :columns="columns"
      :data="tableObject.tableList"
      row-key="id"
      :loading="tableObject.loading"
      :pagination="{ total: tableObject.total }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      @expand-change="handleExpandChange"
    >
      <template #expand="scope">
        <div class="pl-20 pr-3 py-3 bg-gray-100">
          <h2 class="text-xl font-bold mb-3">套餐服务</h2>
          <el-table
            v-loading="skuBindMap[scope.row.id]?.loading"
            :data="skuBindMap[scope.row.id]?.list"
            border
          >
            <el-table-column label="名称" align="center" prop="bindTitle" />
            <el-table-column label="状态" align="center" prop="bindType">
              <template #default="bindTypeScope">
                <el-tag class="ml-2" :type="bindTypeFormatter(bindTypeScope.row.bindType).type">{{
                  bindTypeFormatter(bindTypeScope.row.bindType).text
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="绑定id" align="center" prop="bindId" />
            <!-- <el-table-column label="操作" align="center">
                <template #default="subScope">
                  <el-button
                    link
                    type="primary"
                    @click="openForm('update', subScope.row.id)"
                    v-hasPermi="['train:product-sku-bind:update']"
                  >
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click="openForm('update', subScope.row.id)"
                    v-hasPermi="['train:product-sku-bind:delete']"
                  >
                    解绑
                  </el-button>
                </template>
              </el-table-column> -->
          </el-table>
        </div>
      </template>
      <template #action="scope">
        <el-button link type="primary" @click="openForm('update', scope.row.id)">编辑</el-button>
        <el-button link type="danger" @click="delList(scope.row.id, false)">删除</el-button>
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EditSkuForm ref="formRef" @success="getList" />

  <!-- 分润配置弹窗 -->
  <CheckoutConfigForm ref="checkoutConfigFormRef" @success="getList" />
</template>
